package com.zz.framework.core.base

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.zz.framework.R
import com.zz.framework.core.entity.PausePodcastEvent
import com.zz.framework.core.event.FinishAiEvent
import com.zz.framework.core.event.HttpErrorEvent
import com.zz.framework.core.event.PowerConnectedEvent
import com.zz.framework.core.event.RecordSosInfoEvent
import com.zz.framework.core.event.ShowLockSceenEvent
import com.zz.framework.core.event.ShowSafeTipEvent
import com.zz.framework.core.ext.dp
import com.zz.framework.core.ext.gone
import com.zz.framework.core.ext.invisible
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.print
import com.zz.framework.core.ext.printError
import com.zz.framework.core.ext.toJson
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.visible
import com.zz.framework.core.utils.ActivityStackManager
import com.zz.framework.core.utils.AudioPlayerUtils
import com.zz.framework.core.utils.DeviceUtils
import com.zz.framework.core.utils.IntentBuilder
import com.zz.framework.core.utils.LogUtils
import com.zz.framework.core.utils.ZCountDownTimer
import com.zz.framework.core.utils.ZInterval
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.core.xdialog.XDialog
import com.zz.framework.core.xdialog.listener.OnBindViewListener
import com.zz.framework.databinding.DialogSafeTipBinding
import com.zz.framework.databinding.LoadingLayoutBinding
import com.zz.framework.databinding.SosLayoutBinding
import com.zz.framework.databinding.ViewLockBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.UUID
import kotlin.jvm.java

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/18 13:30.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
open class BaseActivity : AppCompatActivity() {
    val uniqueIdentifier = UUID.randomUUID().toString()

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        enableEdgeToEdge()
        EventBus.getDefault().register(this)
        ActivityStackManager.instance.onCreated(this)
        initProgressLayout()
        initView(savedInstanceState)
        initData()
        initObserver()
    }

    open fun initView(savedInstanceState: Bundle?) {}
    open fun initData() {}
    open fun initObserver() {}

    fun setOnApplyWindowInsetsPadding(rootView: View) {
        ViewCompat.setOnApplyWindowInsetsListener(rootView) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    override fun onResume() {
        super.onResume()
        ("activity---->" + this.javaClass.simpleName).print()
    }

    @Subscribe
    open fun onMessageEvent(e: HttpErrorEvent) {
        onError(e.message)
    }

    @Subscribe
    fun onMessageEvent(e: PowerConnectedEvent) {
        onPowerConnected(e.isCharging)
    }

    open fun onPowerConnected(isCharging: Boolean) {
        if (isCharging) {
            LogUtils.debug("设备正在充电")
            DeviceUtils.clearBluetooth()
            ActivityStackManager.instance.finishActivitiesExcludeMain()
            if (ActivityStackManager.instance.bottomActivity?.javaClass?.simpleName == this.javaClass.simpleName) {
                restart(this)
            }
        }
    }

    fun restart(context: Context) {
        val intent = Intent(context, this::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION
        }
        context.startActivity(intent)
        if (context is Activity) {
            context.overridePendingTransition(R.anim.activity_alpha_in, R.anim.activity_alpha_out)
        }
    }

    fun onError(message: String) {
        message.printError()
        dismissProgress()
    }

    override fun onStart() {
        super.onStart()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        sosInterval.cancel()
        sosTimer.cancel()
        EventBus.getDefault().unregister(this)
        super.onDestroy()
        ActivityStackManager.instance.onDestroyed(this)
    }


    private var mSosLayoutBinding: SosLayoutBinding? = null
    var sosTimer = object : ZCountDownTimer(5 * 1000, 1000) {
        override fun onTick(millisUntilFinished: Long) {
            mSosLayoutBinding?.view1?.text = ((millisUntilFinished / 1000) + 1).toString()
        }

        override fun onFinish() {
            mSosLayoutBinding?.btnCancel?.text = Strings.结束呼救.toLanguage()
            mSosLayoutBinding?.waveView?.setWaveStart(false)
            mSosLayoutBinding?.groupStep1?.invisible()
            mSosLayoutBinding?.tvTip?.visible()
            AudioPlayerUtils.newInstance().playAudioFromAssets("warning.mp3")
            sosInterval.start()
        }
    }

    val sosInterval = object : ZInterval(30 * 1000) {
        override fun onInterval() {
            EventBus.getDefault().post(RecordSosInfoEvent())
        }
    }

    private fun showSosDialog() {
        if (mSosLayoutBinding == null) {
            mSosLayoutBinding = SosLayoutBinding.inflate(LayoutInflater.from(this), window.decorView as ViewGroup?, false).also {
                (window.decorView as ViewGroup?)?.addView(it.root)
            }
        }
        mSosLayoutBinding?.waveView?.setWaveStart(true)
        mSosLayoutBinding?.tvTip?.text = Strings.尊敬的游客您的求救已受理请在原地耐心等待救援.toLanguage()

        sosTimer.start()
        mSosLayoutBinding?.apply {
            groupStep1.visible()
            tvTip.gone()
            btnCancel.text = Strings.取消呼救.toLanguage()
            mSosLayoutBinding?.root?.visible()
            btnCancel.onClick {
                sosTimer.cancel()
                sosInterval.cancel()
                mSosLayoutBinding?.root?.gone()
                if (AudioPlayerUtils.newInstance().isPlaying()) {
                    AudioPlayerUtils.newInstance().stop()
                }
            }
        }
    }

    private var mProgressViewBinding: LoadingLayoutBinding? = null
    private fun initProgressLayout() {
        if (mProgressViewBinding == null) {
            mProgressViewBinding = LoadingLayoutBinding.inflate(LayoutInflater.from(this), window.decorView as ViewGroup?, false)
            mProgressViewBinding?.root?.setOnClickListener({ _: View? -> })
            (window.decorView as ViewGroup?)?.addView(mProgressViewBinding?.root)
            dismissProgress()
        }
    }

    private var mLockScreenBinding: ViewLockBinding? = null
    private fun lockApp() {
        if (mLockScreenBinding == null) {
            mLockScreenBinding = ViewLockBinding.inflate(LayoutInflater.from(this), window.decorView as ViewGroup?, false)
            mLockScreenBinding?.apply {
                tvTitle.text = Strings.您已超出设备使用区域.toLanguage()
                tvContent.text = Strings.您已超出设备使用区域请移步在景区范围内使用该设备.toLanguage()
            }
            mLockScreenBinding?.root?.setOnClickListener({ _: View? -> })
            (window.decorView as ViewGroup?)?.addView(mLockScreenBinding?.root)
        }
        mLockScreenBinding?.root?.visible()
    }

    private fun unlockApp() {
        mLockScreenBinding?.root?.gone()
    }


    @Subscribe
    fun onMessageEvent(e: ShowLockSceenEvent) {
        if (e.isShow) {
            EventBus.getDefault().post(PausePodcastEvent())
            EventBus.getDefault().post(FinishAiEvent())
            lockApp()
        } else {
            unlockApp()
        }
    }
    @Subscribe
    fun onMessageEvent(e: ShowSafeTipEvent) {
        if (ActivityStackManager.instance.topActivity?.uniqueIdentifier == this.uniqueIdentifier) {
            showSafeTipDialog(this)
        }
    }

    private var mProgressTimes = 0
    open fun showProgress() {
        ++mProgressTimes
        mProgressViewBinding?.root?.visible()
    }

    open fun dismissProgress() {
        --mProgressTimes
        if (mProgressTimes <= 0) {
            mProgressViewBinding?.root?.gone()
        }
    }


    fun startParentActivity(clazz: Class<out Fragment>, bundle: Bundle? = null) {
        val builder = IntentBuilder.Builder()
        bundle?.let {
            builder.putExtras(it)
        }
        builder.startParentActivity(this, clazz)
    }

    fun <K, V : Any> startParentActivity(clazz: Class<out Fragment>, vararg params: Pair<K, V>?) {
        val builder = IntentBuilder.Builder()
        params?.forEach {
            builder.putExtra(it?.first.toString(), it?.second?.toJson())
        }
        builder.startParentActivity(this, clazz)
    }

    fun startActivity(clazz: Class<out Activity>) {
        IntentBuilder.Builder().setClass(this, clazz).startActivity()
    }


    override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_CAMERA) {
            // 处理相机按键按下事件
            handleCameraKeyPress()
            return true
        }
        return super.onKeyLongPress(keyCode, event)
    }

//    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
//        if (keyCode == KeyEvent.KEYCODE_CAMERA) {
//            // 处理相机按键按下事件
//            handleCameraKeyPress()
//            return true
//        }
//        return super.onKeyDown(keyCode, event)
//    }


    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.back_left_in, R.anim.back_right_out)
    }

    open fun handleCameraKeyPress() {
        if (ActivityStackManager.instance.topActivity?.uniqueIdentifier == this.uniqueIdentifier) {
            showSosDialog()
        }
        EventBus.getDefault().post(PausePodcastEvent())
    }


    var safeTipDialog: XDialog? = null
    fun showSafeTipDialog(activity: FragmentActivity) {
        safeTipDialog?.dismiss()
        safeTipDialog = XDialog.Builder(activity.supportFragmentManager)
            .setViewBinding(DialogSafeTipBinding::class.java)
            .setWidth(285.dp())
            .setHeight(300.dp())
            .setOnBindViewListener(object : OnBindViewListener<DialogSafeTipBinding> {
                override fun onBind(binding: DialogSafeTipBinding, xDialog: XDialog) {
                    binding.apply {
                        tvTitle.text = Strings.您已进入危险区域请注意安全.toLanguage()
                        btnConfirm.text = Strings.确定.toLanguage()
                        btnConfirm.onClick {
                            xDialog.dismiss()
                        }
                    }
                }
            })
            .setCancelableOutside(true)
            .create()
            .show();
    }
}